package com.imooc.common.controller.select;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.thread.ThreadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;

/**
 * Created by deng_wb on 2020/8/11
 */
@Slf4j
@RequestMapping("/select")
@RestController
public class ThreadSelectController {
    private ExecutorService executor = ThreadUtil.newExecutor();
    private static final Long TIME_OUT = 10000L;


    @RequestMapping("/list")
    public SelectResponse list(){

        return selectData();
    }


    private SelectResponse selectData(){

        TaskSY taskSY = new TaskSY();
        TaskZHF taskZHF = new TaskZHF();

        Future<SelectResponse> futureSY = executor.submit(taskSY);
        Future<SelectResponse> futureZHF = executor.submit(taskZHF);
        HashSet<Future<SelectResponse>> futures = new HashSet<>(Arrays.asList(futureSY, futureZHF));

        // 首先做超时处理
        TimeInterval timer = DateUtil.timer();
        while (true){

            long interval = timer.interval();
            // 超时判断
            if (interval>TIME_OUT){
                futures.forEach(future->future.cancel(true));
                return null;
            }

            for (Future<SelectResponse> future : futures) {
                if (future.isDone()&&!future.isCancelled()){
                    try {
                        return future.get();

                    } catch (InterruptedException e) {
                        log.error("守护线程阻塞被打断");
                        Thread.currentThread().interrupt();
                    } catch (ExecutionException e) {
                        log.error("执行任务出错");
                    }
                }
            }




        }




    }

}
